package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.MessageConstant;
import com.sky.constant.WXConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    /**
     * 用户端-登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) throws JsonProcessingException {
        /*
         * 1.根据小程序传过来的'授权码'去找微信获取用户的唯一标识(openid)
         * 2.openid == null ? 出错或者超时 : 成功
         * 3.根据openid去数据库查询
         * 4.user == null ? 第一次登录,注册 : 登录
         */
        //1.使用httpclient发送get请求到微信服务器
        String openId = getOpenId(userLoginDTO.getCode());
        System.out.println(openId);
        //2.判断openid
        if(openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.根据openid去数据库查询
        User user = userMapper.findUserByOpenid(openId);
        //4.判断user
        if(user == null){
            //注册
            user =  User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }
        return user;
    }

    /**
     * 根据授权码获取openid
     * @param authCode
     * @return
     * @throws JsonProcessingException
     */
    private String getOpenId(String authCode) throws JsonProcessingException {
        Map<String, String> param = new HashMap<String, String>();
        param.put(WXConstant.APP_ID,weChatProperties.getAppid());
        param.put(WXConstant.APP_SECRET,weChatProperties.getSecret());
        param.put(WXConstant.JS_CODE, authCode);
        param.put(WXConstant.GRANT_TYPE,"authorization_code");
        String jsonResult = HttpClientUtil.doGet(URL,param);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,String> map = objectMapper.readValue(jsonResult, Map.class);
        return map.get(WXConstant.OPEN_ID);
    }
}
